package com.gss.plugin.mp.config;

import com.alibaba.druid.filter.Filter;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.wall.WallConfig;
import com.alibaba.druid.wall.WallFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: DYang
 * @since: 2023/8/22
 * @description: druid 配置数据库连接池
 */
@Configuration
public class DruidDataSourceConfig {

    @Autowired
    private MpProperties mpProperties;

    @Bean
    public DataSource dataSource() throws SQLException {
        DruidDataSource dataSource = new DruidDataSource();
        MpProperties.DataSourceConfig dbConfig = mpProperties.getDbConfig();
        dataSource.setName(dbConfig.getName());
        dataSource.setDbType(dbConfig.getDriverType());
        String url = dbConfig.getUrl();
        if (dbConfig.getDbName() != null && !url.contains(dbConfig.getDbName())) {
            url += "/" + dbConfig.getDbName();
        }
        dataSource.setUrl(url);
        dataSource.setUsername(dbConfig.getUsername());
        dataSource.setPassword(dbConfig.getPassword());
        // 数据库配置
        dataSource.setInitialSize(dbConfig.getInitialSize());
        dataSource.setMinIdle(dbConfig.getMinIdle());
        dataSource.setMaxActive(dbConfig.getMaxActive());
        dataSource.setPoolPreparedStatements(dbConfig.isPoolPreparedStatements());
        dataSource.setMaxPoolPreparedStatementPerConnectionSize(dbConfig.getMaxPoolPreparedStatementPerConnectionSize());
        dataSource.setTimeBetweenConnectErrorMillis(dbConfig.getTimeBetweenEvictionRunsMillis());
//        dataSource.setFilters(dbConfig.getFilters());
        dataSource.setValidationQuery(dbConfig.getValidationQuery());
        dataSource.setTestOnBorrow(dbConfig.isTestOnBorrow());
        dataSource.setTestWhileIdle(dbConfig.isTestWhileIdle());
        dataSource.setTestOnReturn(dbConfig.isTestOnReturn());

        List<Filter> filterList = new ArrayList<>();
        filterList.add(this.wallFilter());
        dataSource.setProxyFilters(filterList);

        return dataSource;

    }

    @Bean
    public WallFilter wallFilter() {
        WallFilter wallFilter = new WallFilter();
        wallFilter.setConfig(this.wallConfig());
        return wallFilter;
    }

    @Bean
    public WallConfig wallConfig() {
        WallConfig config = new WallConfig();
        config.setMultiStatementAllow(true);//允许一次执行多条语句
        config.setNoneBaseStatementAllow(true);//允许非基本语句的其他语句
        return config;
    }

}
